package com.szit.adminserver.server.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.szit.adminserver.dao.*;
import com.szit.adminserver.entity.*;
import com.szit.adminserver.server.AdminRoleServer;
import com.szit.util.CodeMsg;
import com.szit.util.Result;
import com.szit.util.vo.AdminRoleInfo;
import com.szit.util.vo.AdminRolePermissionInfo;
import com.szit.util.vo.AdminRoleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;

@Slf4j
@Service
public class AdminRoleServerImpl implements AdminRoleServer {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private AdminRolePermissionMapper adminRolePermissionMapper;

    @Autowired
    private AdminPermissionMapper adminPermissionMapper;

    @Autowired
    private AdminUserRoleMapper adminUserRoleMapper;

    /**
     * 添加角色
     * @param adminRoleInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result insertAdminRole(AdminRoleInfo adminRoleInfo) {
        try {
            if(StringUtils.isEmpty(adminRoleInfo) &&
                    StringUtils.isEmpty(adminRoleInfo.getToken()) &&
                    StringUtils.isEmpty(adminRoleInfo.getName()) &&
                    StringUtils.isEmpty(adminRoleInfo.getOrders()) ){
                log.info("adminUserInfo--------参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }
            AdminUser cAdminUser = adminUserMapper.selectByToken(adminRoleInfo.getToken());
            if(StringUtils.isEmpty(cAdminUser)){
                log.info("--------token无效---------");
                return Result.error(CodeMsg.SESSION_NOT_EXSIST);
            }
            log.info("--------获取当前用户权限---------");
            Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());
            if(cOrder > 2 ){
                log.info("--------当前用户权限不足---------");
                return Result.error(CodeMsg.NO_PERMISSIONS);
            }

            log.info("--------添加角色---------");
            AdminRole adminRole = new AdminRole();
            adminRole.setName(adminRoleInfo.getName());
            adminRole.setTitle(adminRoleInfo.getTitle());
            adminRole.setDescription(adminRoleInfo.getDescription());
            adminRole.setOrders(adminRole.getOrders());
            adminRole.setCtime(new Date());
            adminRoleMapper.insertSelective(adminRole);

            log.info("--------查询刚刚添加的角色id--------");
            AdminRole adminRole1 = adminRoleMapper.selectByName(adminRoleInfo.getName());
            log.info("--------添加角色权限关联--------");
            AdminRolePermission adminRolePermission = new AdminRolePermission();
            adminRolePermission.setPermissionId(adminRoleInfo.getPermissionId());
            adminRolePermission.setRoleId(adminRole1.getRoleId());
            adminRolePermissionMapper.insertSelective(adminRolePermission);

            return Result.success(CodeMsg.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            /*手工回滚异常*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }

    /**
     * 删除角色
     *
     * @param token
     * @param roleId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result deleteRoleById(String token, Integer roleId) {
        try {
            if(StringUtils.isEmpty(token) && StringUtils.isEmpty(roleId)){
                log.info("token----roleId----参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }
            AdminUser cAdminUser = adminUserMapper.selectByToken(token);
            if(StringUtils.isEmpty(cAdminUser)){
                log.info("--------token无效---------");
                return Result.error(CodeMsg.SESSION_NOT_EXSIST);
            }
            log.info("--------获取当前用户权限---------");
            Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());
            if(cOrder > 2 ){
                log.info("--------当前用户权限不足---------");
                return Result.error(CodeMsg.NO_PERMISSIONS);
            }
            log.info("--------查询角色是否绑定过用户---------");
            Integer num = adminUserRoleMapper.selectCountByRoleId(roleId);
            if(num > 0){
                log.info("--------用户在使用该角色无法删除---------");
                return Result.error(CodeMsg.UNBIND_ROLE_USER);
            }
            log.info("--------删除角色---------");
            adminRoleMapper.deleteByPrimaryKey(roleId);

            return Result.success(CodeMsg.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            /*手工回滚异常*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }

    /**
     * 更新角色
     *
     * @param adminRoleInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateRoleById(AdminRoleInfo adminRoleInfo) {
        try {
            if(StringUtils.isEmpty(adminRoleInfo) &&
                    StringUtils.isEmpty(adminRoleInfo.getToken())){
                log.info("adminPermissionInfo--------参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }
            AdminUser cAdminUser = adminUserMapper.selectByToken(adminRoleInfo.getToken());
            if(StringUtils.isEmpty(cAdminUser)){
                log.info("--------token无效---------");
                return Result.error(CodeMsg.SESSION_NOT_EXSIST);
            }
            log.info("--------获取当前用户权限---------");
            Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());
            if(cOrder > 2 ){
                log.info("--------当前用户权限不足---------");
                return Result.error(CodeMsg.NO_PERMISSIONS);
            }
            log.info("--------查询角色是否存在---------");
            AdminRole adminRole = adminRoleMapper.selectByPrimaryKey(adminRoleInfo.getRoleId());
            if(StringUtils.isEmpty(adminRole)){
                log.info("--------角色不存在---------");
                return Result.error(CodeMsg.NOT_FIND_DATA);
            }
            log.info("--------修改权限---------");
            if(!StringUtils.isEmpty(adminRoleInfo.getName())){
                adminRole.setName(adminRoleInfo.getName());
            }
            if(!StringUtils.isEmpty(adminRoleInfo.getTitle())){
                adminRole.setTitle(adminRoleInfo.getTitle());
            }
            if(!StringUtils.isEmpty(adminRoleInfo.getDescription())){
                adminRole.setDescription(adminRoleInfo.getDescription());
            }
            if(!StringUtils.isEmpty(adminRoleInfo.getOrders())){
                adminRole.setOrders(adminRoleInfo.getOrders());
            }
            adminRoleMapper.updateByPrimaryKeySelective(adminRole);

            return Result.success(CodeMsg.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            /*手工回滚异常*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }

    /**
     * 查找角色列表
     *
     * @param token
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Result selectAllAdminRole(String token, Integer pageNum, Integer pageSize) {
        try {
            if(StringUtils.isEmpty(token)){
                log.info("token--------参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }
            if(StringUtils.isEmpty(pageNum)){
                pageNum = 1;
            }
            if(StringUtils.isEmpty(pageSize)){
                pageSize = 10;
            }
            AdminUser cAdminUser = adminUserMapper.selectByToken(token);
            if(StringUtils.isEmpty(cAdminUser)){
                log.info("--------token无效---------");
                return Result.error(CodeMsg.SESSION_NOT_EXSIST);
            }
            log.info("--------获取当前用户权限---------");
            Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());
            if(cOrder > 3 ){
                log.info("--------当前用户权限不足---------");
                return Result.error(CodeMsg.NO_PERMISSIONS);
            }

            log.info("--------查询所有角色---------");
            /*分页插件 传入页数和每页数量*/
            PageHelper.startPage(pageNum, pageSize);
            ArrayList<AdminRoleVo> list = adminRoleMapper.selectPermissionIdAndAllAdminRole();
            PageInfo pageInfo = new PageInfo(list);

            return Result.success(pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }

    /**
     * 更改角色权限
     *
     * @param adminRolePermissionInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateRolePermissionByRoleId(AdminRolePermissionInfo adminRolePermissionInfo) {
        try {
            if(StringUtils.isEmpty(adminRolePermissionInfo) &&
                    StringUtils.isEmpty(adminRolePermissionInfo.getToken()) &&
                    StringUtils.isEmpty(adminRolePermissionInfo.getPermissionId()) &&
                    StringUtils.isEmpty(adminRolePermissionInfo.getRoleId())){
                log.info("adminUserInfo--------参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }
            AdminUser cAdminUser = adminUserMapper.selectByToken(adminRolePermissionInfo.getToken());
            if(StringUtils.isEmpty(cAdminUser)){
                log.info("--------token无效---------");
                return Result.error(CodeMsg.SESSION_NOT_EXSIST);
            }
            log.info("--------获取当前用户权限---------");
            Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());
            if(cOrder > 2 ){
                log.info("--------当前用户权限不足---------");
                return Result.error(CodeMsg.NO_PERMISSIONS);
            }

            log.info("--------查询该角色权限关联--------");
            AdminRolePermission adminRolePermission = adminRolePermissionMapper.selectByRoleId(adminRolePermissionInfo.getRoleId());
            if(StringUtils.isEmpty(adminRolePermission)){
                log.info("--------角色无权限，添加权限--------");
                adminRolePermission = new AdminRolePermission();
                adminRolePermission.setRoleId(adminRolePermissionInfo.getRoleId());
                adminRolePermission.setPermissionId(adminRolePermissionInfo.getPermissionId());
                log.info("--------新增角色权限--------");
                adminRolePermissionMapper.insertSelective(adminRolePermission);
            }else {
                log.info("--------角色有权限，更新权限--------");
                adminRolePermission.setPermissionId(adminRolePermissionInfo.getPermissionId());
                log.info("--------更改角色权限--------");
                adminRolePermissionMapper.updateByPrimaryKeySelective(adminRolePermission);
            }

            return Result.success(CodeMsg.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            /*手工回滚异常*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }

    /**
     * 删除角色权限
     *
     * @param adminRolePermissionInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result deleteAdminRolePermission(AdminRolePermissionInfo adminRolePermissionInfo) {
        try {
            if(StringUtils.isEmpty(adminRolePermissionInfo) &&
                    StringUtils.isEmpty(adminRolePermissionInfo.getToken()) &&
                    StringUtils.isEmpty(adminRolePermissionInfo.getRoleId())){
                log.info("adminRolePermissionInfo--------参数为空");
                return Result.error(CodeMsg.PARAMETER_ISNULL);
            }
            AdminUser cAdminUser = adminUserMapper.selectByToken(adminRolePermissionInfo.getToken());
            if(StringUtils.isEmpty(cAdminUser)){
                log.info("--------token无效---------");
                return Result.error(CodeMsg.SESSION_NOT_EXSIST);
            }
            log.info("--------获取当前用户权限---------");
            Long cOrder =  adminPermissionMapper.selectOrdersByUserId(cAdminUser.getUserId());
            if(cOrder > 2 ){
                log.info("--------当前用户权限不足---------");
                return Result.error(CodeMsg.NO_PERMISSIONS);
            }

            log.info("--------查询该角色权限关联--------");
            AdminRolePermission adminRolePermission = adminRolePermissionMapper.selectByRoleId(adminRolePermissionInfo.getRoleId());
            if(StringUtils.isEmpty(adminRolePermission)){
                log.info("--------角色无绑定权限---------");
                return Result.error(CodeMsg.NOT_FIND_DATA);
            }

            log.info("--------角色删除权限---------");
            adminRolePermissionMapper.deleteByPrimaryKey(adminRolePermission.getRolePermissionId());

            return Result.success(CodeMsg.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            /*手工回滚异常*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(CodeMsg.SERVER_EXCEPTION);
        }
    }
}
